package com.qxzn.app.personalcenter.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.BindRobotUserBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.personalcenter.R;
import com.qxzn.app.personalcenter.R2;
import com.qxzn.app.personalcenter.adapter.BindRobotUserAdapter;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 绑定机器人的用户列表
 */
public class ToAuthUserAddRobotActivity extends BaseActivity {

    @BindView(R2.id.lrv_to_auth_user)
    LRecyclerView lrvToAuthUser;
    @BindView(R2.id.view_empty)
    View viewEmpty;
    private LRecyclerViewAdapter recyclerViewAdapter;
    private BindRobotUserAdapter adapter;
    private List<BindRobotUserBean.DataBean> dataList = new ArrayList();
    private int page = 1;
    private int pageSize = 10;

    @Override
    protected int initLayout() {
        return R.layout.activity_to_authorized_users;
    }

    @Override
    protected void initView() {
        adapter = new BindRobotUserAdapter(this, dataList);
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                AppUtil.showLog("点击位置：" + position);
                if ("-1".equals(dataList.get(position).getRoles())) {
                    showDialog("授权绑定", "是否授权该用户绑定机器人？", "取消", "确认授权", null, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            authUserBindRobot(dataList.get(position).getUsername());
                        }
                    });
                } else if ("1".equals(dataList.get(position).getRoles())) {
//                    showDialog("解除绑定", "是否解除该用户绑定机器人？", "取消", "确认解除", null, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            delAuthUserBindRobot(dataList.get(position).getUsername());
//                        }
//                    });
                }
            }
        });
        lrvToAuthUser.setLayoutManager(new LinearLayoutManager(this));
        lrvToAuthUser.setEmptyView(viewEmpty);
        lrvToAuthUser.setAdapter(recyclerViewAdapter);
        lrvToAuthUser.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                AppUtil.showLog("setOnRefreshListener");
                page = 1;
                getData();
            }
        });
        lrvToAuthUser.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                AppUtil.showLog("setOnLoadMoreListener");
                page++;
                getData();
            }
        });
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("绑定机器人的用户");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        lrvToAuthUser.refresh();
    }

    @OnClick(R2.id.view_empty)
    public void onViewClicked() {
        lrvToAuthUser.refresh();
    }

    private void getData() {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                lrvToAuthUser.refreshComplete(pageSize);
//            }
//        }, 1000);
//        for (int i = (page - 1) * pageSize; i < page * pageSize; i++) {
//            dataList.add(new BindRobotUserBean.DataBean());
//        }
//        recyclerViewAdapter.notifyDataSetChanged();
//        recyclerViewAdapter.notifyItemRangeChanged((page - 1) * pageSize, pageSize);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"page\":\"" + page + "\"}");
        Call<BindRobotUserBean> call = HttpRequest.getService().getBindRobotUser(body);
        call.enqueue(new Callback<BindRobotUserBean>() {
            @Override
            public void onResponse(Call<BindRobotUserBean> call, Response<BindRobotUserBean> response) {
                lrvToAuthUser.refreshComplete(pageSize);
                BindRobotUserBean bean = response.body();
                if (bean != null) {
                    List<BindRobotUserBean.DataBean> deviceList = bean.getData();
                    if (deviceList != null) {
                        if (page == 1) {
                            dataList.clear();
                        }
                        dataList.addAll(deviceList);
                        adapter.notifyDataSetChanged();
                        recyclerViewAdapter.notifyDataSetChanged();
                        return;
                    }
                }
                if (bean != null && bean.getCode() != 200 && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<BindRobotUserBean> call, Throwable t) {
                lrvToAuthUser.refreshComplete(pageSize);
                AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void authUserBindRobot(String username) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + username + "\",\"roles\":\"" + 1 + "\"}");
        Call<BaseBean> call = HttpRequest.getService().deviceAuth(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                lrvToAuthUser.refreshComplete(pageSize);
                BaseBean bean = response.body();
                if (bean != null) {
                    if (bean.getCode() == 200) {
                        if (!TextUtils.isEmpty(bean.getMsg())) {
                            AppUtil.showToast(ToAuthUserAddRobotActivity.this, bean.getMsg());
                        } else {
                            AppUtil.showToast(ToAuthUserAddRobotActivity.this, "授权成功");
                        }
                        lrvToAuthUser.refresh();
                        return;
                    }
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                lrvToAuthUser.refreshComplete(pageSize);
                AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void delAuthUserBindRobot(String username) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + username + "\"}");
        Call<BaseBean> call = HttpRequest.getService().delDeviceAuth(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                lrvToAuthUser.refreshComplete(pageSize);
                BaseBean bean = response.body();
                if (bean != null) {
                    if (bean.getCode() == 200) {
                        if (!TextUtils.isEmpty(bean.getMsg())) {
                            AppUtil.showToast(ToAuthUserAddRobotActivity.this, bean.getMsg());
                        } else {
                            AppUtil.showToast(ToAuthUserAddRobotActivity.this, "解除绑定成功");
                        }
                        lrvToAuthUser.refresh();
                        return;
                    }
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                lrvToAuthUser.refreshComplete(pageSize);
                AppUtil.showToast(ToAuthUserAddRobotActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

}
